<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="请输入登录名"
        v-model="queryForm.name"
        maxlength="15"
      >
      </el-input>
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="请输入手机号"
        v-model="queryForm.phone"
        maxlength="11"
      >
      </el-input>
      <el-select
        clearable
        style="width: 150px"
        class="filter-item"
        v-model="queryForm.status"
        placeholder="请选择用户状态"
      >
        <el-option
          v-for="(val, key) in statusOptions"
          :key="key"
          :label="val"
          :value="key"
        >
        </el-option>
      </el-select>
      <el-select
        clearable
        style="width: 150px"
        class="filter-item"
        v-model="queryForm.attribute"
        placeholder="请选择用户类型"
      >
        <el-option
          v-for="(val, key) in attributeOptions"
          :key="key"
          :label="val"
          :value="key"
        >
        </el-option>
      </el-select>
      <el-button
        class="filter-item"
        @click="doQuery"
        type="primary"
        icon="el-icon-search"
        title="搜索"
        >搜索</el-button
      >
      <el-button
        v-permission="'operateUser:add'"
        class="filter-item"
        style="margin-left: 10px;"
        @click="openCreateDialog"
        type="success"
        icon="el-icon-plus"
        title="新增"
        >新增</el-button
      >
    </div>
    <el-table
      v-loading="loading"
      @sort-change="handleSortChange"
      :data="records"
      style="width: 100%"
    >
      <el-table-column prop="rowId" label="ID" width="100" align="center">
      </el-table-column>
      <el-table-column prop="name" label="登录名" width="150" align="center">
      </el-table-column>
      <el-table-column prop="realName" label="真名" width="150" align="center">
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="150" align="center">
      </el-table-column>
      <el-table-column prop="mail" label="邮箱" width="250" align="center">
      </el-table-column>
      <!-- <el-table-column
        prop="roleName"
        label="角色">
      </el-table-column> -->
      <el-table-column
        prop="attribute"
        label="用户类型"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          {{ Dicts.USER_ATTRIBUTE[scope.row.attribute] }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="150" align="center">
        <template slot-scope="scope">
          {{ Dicts.CONSUMER_STATUS[scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        sortable="custom"
        sort-by="create_time"
        label="创建时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        width="300"
        align="center"
        label="操作"
        class-name="small-padding"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="'user:update'"
            @click="editDialog(scope.row)"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            circle
            title="修改"
          ></el-button>
          <el-button
            v-permission="'user:roleDialog'"
            @click="roleDialog(scope.row)"
            type="warning"
            size="mini"
            icon="el-icon-setting"
            circle
            title="赋权"
          ></el-button>
          <el-button
            v-permission="'user:resetPassword'"
            @click="editExample(scope.row)"
            type="primary"
            size="mini"
            icon="el-icon-refresh"
            circle
            title="重置密码"
          ></el-button>
          <template v-if="scope.row.status == 1">
            <el-button
              v-permission="'user:disabled'"
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.rowId)"
              icon="el-icon-close"
              circle
              title="禁用"
            ></el-button>
          </template>
          <template v-else>
            <el-button
              v-permission="'user:active'"
              size="mini"
              type="success"
              @click="active(scope.row.rowId)"
              icon="el-icon-check"
              circle
              title="激活"
            ></el-button>
          </template>
          <el-button
            v-permission="'operateUser:cancellation'"
            @click="cancellation(scope.row.rowId)"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            circle
            title="注销"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryForm.total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="`重置密码`"
      :visible.sync="passwordFormVisible"
      width="25%"
    >
      <el-form
        :model="passwordForm"
        label-width="90px"
        :rules="passwordFormRules"
        ref="passwordForm"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            type="password"
            v-model="passwordForm.password"
            auto-complete="off"
            placeholder="请输入6-20位且包含大小写英文字母和数字的密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="resetPassword">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="`修改`"
      :visible.sync="dialogEditFormVisible"
      width="40%"
    >
      <el-form
        :model="editForm"
        label-width="90px"
        :rules="editFormRules"
        ref="editForm"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="真实姓名" prop="realName">
              <el-input
                v-model="editForm.realName"
                auto-complete="off"
                maxlength="15"
                placeholder="请输入中文"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="手机号">
              <el-input
                v-model="editForm.phone"
                auto-complete="off"
                placeholder="请输入11位手机号"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item
              label="邮箱"
              prop="email"
              :rules="[
                {
                  type: 'email',
                  message: '请输入正确的邮箱',
                  trigger: ['blur', 'change']
                }
              ]"
            >
              <el-input
                v-model="editForm.email"
                auto-complete="off"
                maxlength="64"
                placeholder="xxx@xxx.com"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="小区" prop="communityId" v-if="isShow">
              <el-select
                v-model="editForm.communityId"
                filterable
                multiple
                placeholder="请选择"
                style="width: 100%;"
              >
                <el-option
                  v-for="(item, index) in communitys"
                  :key="index"
                  :label="item.name"
                  :value="item.rowId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editOperateUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="`新增`" :visible.sync="dialogAddFormVisible" width="50%">
      <el-form
        :model="addForm"
        label-width="90px"
        :rules="addFormRules"
        ref="addForm"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="登录名" prop="name">
              <el-input
                v-model="addForm.name"
                auto-complete="off"
                placeholder="请输入4-20位数字或字母"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="真实姓名" prop="realName">
              <el-input
                v-model="addForm.realName"
                auto-complete="off"
                maxlength="15"
                placeholder="请输入中文"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="密码" prop="passwordCheck">
              <el-input
                type="password"
                v-model="addForm.passwordCheck"
                auto-complete="off"
                placeholder="6-20位且包含大小写英文字母和数字"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                type="password"
                v-model="addForm.confirmPassword"
                auto-complete="off"
                placeholder="6-20位且包含大小写英文字母和数字"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="手机" prop="phone">
              <el-input
                v-model="addForm.phone"
                auto-complete="off"
                placeholder="请输入11位手机号"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item
              label="邮箱"
              prop="email"
              :rules="[
                {
                  type: 'email',
                  message: '请输入正确的邮箱',
                  trigger: ['blur', 'change']
                }
              ]"
            >
              <el-input
                v-model="addForm.email"
                auto-complete="off"
                maxlength="64"
                placeholder="xxx@xxx.com"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="所属企业:" prop="bussinessId">
              <el-select
                v-model="addForm.bussinessId"
                placeholder="请选择用户所属企业"
                style="width: 100%;"
                filterable
              >
                <el-option
                  v-for="(item, index) in bussinesss"
                  :key="index"
                  :value="item.rowId"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="用户类型:" prop="attribute">
              <el-select
                v-model="addForm.attribute"
                placeholder="请选择用户类型"
                style="width: 100%;"
                filterable
              >
                <el-option
                  v-for="(item, index) in roles"
                  :key="index"
                  :value="item.code"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOperateUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="`赋权`"
      :visible.sync="dialogRoleFormVisible"
      width="25%"
    >
      <el-form
        :model="roleForm"
        label-width="90px"
        :rules="roleFormRules"
        ref="roleForm"
      >
        <el-radio-group
          v-model="checkedRoles"
          @change="handlecheckedRolesChange"
        >
          <el-form-item label="角色" prop="roleId">
            <el-radio
              v-for="item in roles"
              :label="item.rowId"
              :key="item.name"
              >{{ item.name }}</el-radio
            >
          </el-form-item>
          <!-- <br>
            <el-form-item
          label="外部角色"
          prop="roleId"
        >
             <el-radio
              v-for="item in roles"
              :label="item.rowId"
              :key="item.name"
              v-if="item.type=='2'"
            >{{ item.name }}</el-radio>
            </el-form-item> -->
        </el-radio-group>
        <!-- </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="giveRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryOperateUser,
  deleteOperateUser,
  disableOperateUser,
  addOperateUser,
  editUserOrOperateUser,
  queryRole,
  giveRole,
  selectRoleByUserId,
  resetPassword,
  cancellationOperateUser,
  getBussiness
} from '@/api/consumer'
import md5 from 'js-md5'

export default {
  name: 'OperateUser',
  data() {
    var checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入登录名'))
      }
      if (!/^[0-9a-zA-Z]{4,20}$/.test(value)) {
        callback(new Error('请输入4-20位数字或字母'))
      }
      callback()
    }
    var checkRealName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入真实姓名'))
      }
      if (value.indexOf(' ') >= 0) {
        callback(new Error('请勿输入带有空格的姓名'))
      }
      if (!/^[\u4e00-\u9fa5]+$/.test(value)) {
        callback(new Error('请输入正确的姓名'))
      }
      callback()
    }
    var checkPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入密码'))
      }
      if (!/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(.{6,20})$/.test(value)) {
        callback(new Error('请输入6-20位且包含大小写英文字母和数字的密码!'))
      } else {
        callback()
      }
    }
    var checkConfirmPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入确认密码'))
      }
      if (value !== this.addForm.passwordCheck) {
        callback(new Error('两次密码不一致'))
      } else {
        callback()
      }
    }
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号'))
      }
      if (!/^(1[345789]\d{9})$/.test(value)) {
        callback(new Error('请输入正确的号码'))
      } else {
        callback()
      }
    }
    return {
      isShow: false,
      isService: false,
      passwordFormVisible: false,
      checkedRoles: [],
      dialogEditFormVisible: false,
      dialogAddFormVisible: false,
      dialogRoleFormVisible: false,
      loading: false,
      passwordForm: {},
      modifyForm: {},
      passwordFormRules: {
        password: [
          { required: true, validator: checkPassword, trigger: 'blur' }
        ]
      },
      editForm: {
        rowId: undefined
      },
      editFormRules: {
        phone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
        realName: [
          { required: true, validator: checkRealName, trigger: 'blur' }
        ],
        attribute: [
          { required: true, message: '请选择用户类型', trigger: 'blur' }
        ],
        communityId: [
          { required: true, message: '请选择小区', trigger: 'blur' }
        ]
      },
      roleFormRules: {},
      addFormRules: {
        name: [{ required: true, validator: checkName, trigger: 'blur' }],
        realName: [
          { required: true, validator: checkRealName, trigger: 'blur' }
        ],
        passwordCheck: [
          { required: true, validator: checkPassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: checkConfirmPassword, trigger: 'blur' }
        ],
        phone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
        attribute: [
          { required: true, message: '请选择用户类型', trigger: 'blur' }
        ],
        communityId: [
          { required: true, message: '请选择小区', trigger: 'blur' }
        ],
        communityServiceId: [
          { required: true, message: '请选择小区', trigger: 'blur' }
        ],

        bussinessId: [
          { required: true, message: '请选择所属企业', trigger: 'blur' }
        ]
      },
      queryForm: {
        current: 1,
        pages: 0,
        total: 0,
        size: 10,
        ascs: '',
        descs: '',
        importance: undefined,
        title: undefined
      },
      addForm: {
        name: '',
        realName: '',
        password: '',
        phone: '',
        email: '',
        communityId: [],
        communityServiceId: [],
        attribute: '',
        passwordCheck: ''
      },
      deleteForm: {
        rowId: '',
        status: ''
      },
      realForm: {},
      roleForm: {
        userId: '',
        roleId: ''
      },
      communitys: [],
      attributeOptions: Dicts.USER_ATTRIBUTE,
      statusOptions: Dicts.CONSUMER_STATUS,
      records: [],
      roles: [],
      bussinesss: {}
    }
  },
  created() {
    this.doQuery()
  },
  methods: {
    handleSortChange({ column, prop, order }) {
      this.queryForm.ascs = ''
      this.queryForm.descs = ''
      if (order) {
        if (order === 'ascending') {
          this.queryForm.ascs = column.sortBy
        } else {
          this.queryForm.descs = column.sortBy
        }
      }
      this.queryForm.current = 0
      this.doQuery()
    },
    handleCurrentChange(current) {
      this.queryForm.current = current
      this.doQuery()
    },
    handleSizeChange(size) {
      this.queryForm.size = size
      this.doQuery()
    },
    doQuery() {
      this.loading = true
      queryOperateUser(this.queryForm).then(({ data: { data } }) => {
        this.queryForm.current = data.current
        this.queryForm.pages = data.pages
        this.queryForm.total = data.total
        this.queryForm.size = data.size
        this.records = data.records
        this.loading = false
      })
    },
    handleDelete(rowId) {
      this.deleteForm.rowId = rowId
      this.deleteForm.status = 0
      this.$confirm('确认禁用此账号?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        disableOperateUser(this.deleteForm).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    active(rowId) {
      this.deleteForm.rowId = rowId
      this.deleteForm.status = 1
      this.$confirm('确认激活此账号?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOperateUser(this.deleteForm).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    editDialog({ rowId, realName, phone, mail, attribute }) {
      this.openResetPasswordDialog()
      if (attribute === 'property') {
        this.isShow = true
      } else {
        this.isShow = false
        this.editForm = {
          rowId: rowId,
          realName: realName,
          phone: phone,
          email: mail,
          attribute: attribute
        }
      }
    },
    roleDialog({ rowId }) {
      this.checkedRoles = []
      queryRole().then(({ data: { code, data, msg } }) => {
        if (code === 0) {
          this.roles = data
          this.openRoleDialog()
          this.roleForm = {
            userId: rowId
          }
        }
      })
      selectRoleByUserId(rowId).then(({ data: { code, data, msg } }) => {
        if (code === 0) {
          this.checkedRoles = data
        }
      })
    },
    openRoleDialog() {
      this.roleForm = {}
      this.dialogRoleFormVisible = true
      this.$refs.roleForm && this.$refs.roleForm.resetFields()
    },
    openResetPasswordDialog() {
      this.editForm = {}
      this.dialogEditFormVisible = true
      this.$refs.editForm && this.$refs.editForm.resetFields()
    },
    openCreateDialog() {
      this.loading = true
      getBussiness().then(({ data: { code, data, msg } }) => {
        this.loading = false
        if (code === 0) {
          this.bussinesss = data.bussinesss
          this.roles = data.roles
        }
      })
      this.addForm = {}
      this.dialogAddFormVisible = true
      this.$refs.addForm && this.$refs.addForm.resetFields()
    },
    addOperateUser() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.realForm.name = this.addForm.name
          this.realForm.realName = this.addForm.realName
          this.realForm.password = md5(this.addForm.passwordCheck)
          this.realForm.phone = this.addForm.phone
          this.realForm.mail = this.addForm.email
          this.realForm.attribute = this.addForm.attribute
          this.realForm.communityId = this.addForm.communityId
          this.realForm.communityServiceId = this.addForm.communityServiceId
          this.realForm.bussinessId = this.addForm.bussinessId
          addOperateUser(this.realForm).then(
            ({ data: { data, msg, code } }) => {
              if (code === 0) {
                this.doQuery()
                this.dialogAddFormVisible = false
              }
              this.$message({
                showClose: true,
                message: '新增成功!',
                type: code === 0 ? 'success' : 'error'
              })
            }
          )
        } else {
          return false
        }
      })
    },
    editOperateUser() {
      this.editForm.mail = this.editForm.email
      this.$refs.editForm.validate(valid => {
        if (valid) {
          editUserOrOperateUser(this.editForm).then(
            ({ data: { data, msg, code } }) => {
              if (code === 0) {
                this.doQuery()
                this.dialogEditFormVisible = false
              }
              this.$message({
                showClose: true,
                message: msg,
                type: code === 0 ? 'success' : 'error'
              })
            }
          )
        } else {
          return false
        }
      })
    },
    handlecheckedRolesChange(val) {
      this.roleForm.roleIds = val
    },
    giveRole() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          giveRole(this.roleForm).then(({ data: { data, msg, code } }) => {
            if (code === 0) {
              this.doQuery()
              this.dialogRoleFormVisible = false
            }
            this.$message({
              showClose: true,
              message: '赋权成功!',
              type: code === 0 ? 'success' : 'error'
            })
          })
        } else {
          return false
        }
      })
    },
    addAttributeChenge() {
      if (this.addForm.attribute === 'property') {
        this.isShow = true
        this.isService = false
        this.addForm.communityServiceId = ''
      } else if (this.addForm.attribute === 'community_service') {
        this.isService = true
        this.isShow = false
        this.addForm.communityId = ''
      } else {
        this.isShow = false
        this.isService = false
      }
    },
    updateAttributeChenge() {
      if (this.editForm.attribute === 'property') {
        this.isShow = true
      } else {
        this.isShow = false
      }
    },
    editExample({ rowId }) {
      this.resetPasswordDialog()
      this.passwordForm = {
        rowId: rowId
      }
    },
    resetPasswordDialog() {
      this.passwordForm = {}
      this.passwordFormVisible = true
      this.$refs.passwordForm && this.$refs.passwordForm.resetFields()
    },
    resetPassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.modifyForm.password = md5(this.passwordForm.password)
          this.modifyForm.rowId = this.passwordForm.rowId
          resetPassword(this.modifyForm).then(
            ({ data: { data, msg, code } }) => {
              if (code === 0) {
                this.doQuery()
                this.passwordFormVisible = false
              }
              this.$message({
                showClose: true,
                message: msg,
                type: code === 0 ? 'success' : 'error'
              })
            }
          )
        } else {
          return false
        }
      })
    },
    cancellation(rowId) {
      this.$confirm('确认要注销此账号?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancellationOperateUser(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: '该用户注销成功',
            type: 'success'
          })
        })
      })
    }
  },
  components: {}
}
</script>

<style scoped></style>
